"""
API网关统一路由模块
==================

基于RedFire框架的统一路由定义
整合所有路由需求，提供清晰的API结构
"""

import logging
from typing import Dict, Any, Optional
from datetime import datetime
from fastapi import APIRouter, Request, Response, HTTPException, Depends
from fastapi.responses import JSONResponse

from .dependencies import (
    get_gateway_service,
    get_route_service,
    get_load_balancer_service,
    get_container  # 使用容器获取框架标准监控功能
)
from .services.websocket_proxy import get_websocket_proxy
# 移除冗余的监控服务导入 - 将使用框架标准功能
# get_health_check_service,
# get_metrics_service

logger = logging.getLogger(__name__)


def create_gateway_routes() -> APIRouter:
    """
    创建API Gateway路由
    
    Returns:
        APIRouter: 路由器实例
    """
    router = APIRouter()
    
    # ==================== 管理端点（必须先注册具体路由）====================
    
    @router.get("/health", tags=["管理"])
    async def gateway_health(
        container = Depends(get_container)
    ) -> Dict[str, Any]:
        """
        网关健康检查 - 使用框架标准功能
        """
        try:
            # 使用框架标准的健康检查
            import time
            
            # 基本健康检查
            health_details = {
                "gateway": "healthy",
                "database": "unknown",
                "cache": "unknown",
                "event_bus": "unknown"
            }
            
            # 检查数据库连接
            try:
                db_manager = container.database_manager()
                health_details["database"] = "healthy"
            except Exception as e:
                health_details["database"] = f"unhealthy: {str(e)}"
            
            # 检查缓存服务
            try:
                cache_service = container.cache_service()
                health_details["cache"] = "healthy"
            except Exception as e:
                health_details["cache"] = f"unhealthy: {str(e)}"
            
            # 检查事件总线
            try:
                event_bus = container.event_bus()
                health_details["event_bus"] = "healthy"
            except Exception as e:
                health_details["event_bus"] = f"unhealthy: {str(e)}"
            
            # 判断整体状态
            overall_healthy = all("healthy" in status for status in health_details.values())
            
            return {
                "status": "healthy" if overall_healthy else "unhealthy",
                "timestamp": time.time(),
                "details": health_details,
                "version": "1.0.0",
                "service": "api-gateway"
            }
        except Exception as e:
            logger.error(f"Health check error: {e}", exc_info=True)
            return {
                "status": "unhealthy",
                "error": str(e),
                "version": "1.0.0",
                "service": "api-gateway"
            }
    
    @router.get("/health/services", tags=["管理"])
    async def services_health(
        gateway_service = Depends(get_gateway_service)
    ) -> Dict[str, Any]:
        """
        所有后端服务健康检查 - 使用框架标准功能
        """
        try:
            import time
            from .config import get_api_gateway_config
            
            config = get_api_gateway_config()
            services_status = {}
            healthy_count = 0
            total_count = 0
            
            # 检查配置中的每个服务
            for service_name, instances in config.services.items():
                total_count += 1
                service_healthy = False
                
                # 检查服务的每个实例
                for instance in instances:
                    try:
                        # 这里可以实现实际的健康检查逻辑
                        # 暂时简化为配置检查
                        if instance.host and instance.port:
                            service_healthy = True
                            break
                    except Exception:
                        continue
                
                services_status[service_name] = {
                    "status": "healthy" if service_healthy else "unhealthy",
                    "instances": len(instances)
                }
                
                if service_healthy:
                    healthy_count += 1
            
            return {
                "timestamp": time.time(),
                "services": services_status,
                "summary": {
                    "total": total_count,
                    "healthy": healthy_count,
                    "unhealthy": total_count - healthy_count
                }
            }
        except Exception as e:
            logger.error(f"Services health check error: {e}", exc_info=True)
            return {
                "error": str(e),
                "services": {},
                "summary": {"total": 0, "healthy": 0, "unhealthy": 0}
            }
    
    @router.get("/metrics", tags=["管理"])
    async def gateway_metrics(
        container = Depends(get_container)
    ) -> Dict[str, Any]:
        """
        网关指标信息 - 使用框架标准功能
        """
        try:
            import time
            
            # 基本系统指标（简化版，避免依赖psutil）
            metrics = {
                "timestamp": time.time(),
                "service": "api-gateway",
                "version": "1.0.0",
                "system": {
                    "status": "running"
                },
                "gateway": {
                    "status": "running",
                    "uptime": time.time()  # 简化的运行时间
                },
                "components": {}
            }
            
            # 检查各组件状态
            try:
                cache_service = container.cache_service()
                metrics["components"]["cache"] = {"status": "healthy"}
            except Exception as e:
                metrics["components"]["cache"] = {"status": "unhealthy", "error": str(e)}
            
            try:
                event_bus = container.event_bus()
                metrics["components"]["event_bus"] = {"status": "healthy"}
            except Exception as e:
                metrics["components"]["event_bus"] = {"status": "unhealthy", "error": str(e)}
            
            try:
                db_manager = container.database_manager()
                metrics["components"]["database"] = {"status": "healthy"}
            except Exception as e:
                metrics["components"]["database"] = {"status": "unhealthy", "error": str(e)}
            
            return metrics
        except Exception as e:
            logger.error(f"Metrics error: {e}", exc_info=True)
            return {
                "error": str(e),
                "timestamp": time.time(),
                "service": "api-gateway"
            }
    
    @router.get("/routes", tags=["管理"])
    async def list_routes(
        route_service = Depends(get_route_service)
    ) -> Dict[str, Any]:
        """
        列出所有路由配置
        """
        try:
            routes = await route_service.list_routes()
            return {
                "routes": routes,
                "total": len(routes)
            }
        except Exception as e:
            logger.error(f"List routes error: {e}", exc_info=True)
            return {
                "error": str(e),
                "routes": [],
                "total": 0
            }
    
    @router.get("/services", tags=["管理"])
    async def list_services(
        load_balancer_service = Depends(get_load_balancer_service)
    ) -> Dict[str, Any]:
        """
        列出所有服务实例
        """
        try:
            services = await load_balancer_service.list_services()
            return {
                "services": services,
                "total": len(services)
            }
        except Exception as e:
            logger.error(f"List services error: {e}", exc_info=True)
            return {
                "error": str(e),
                "services": {},
                "total": 0
            }
    
    @router.get("/services/{service_name}/instances", tags=["管理"])
    async def list_service_instances(
        service_name: str,
        load_balancer_service = Depends(get_load_balancer_service)
    ) -> Dict[str, Any]:
        """
        列出指定服务的所有实例
        """
        try:
            instances = await load_balancer_service.list_service_instances(service_name)
            return {
                "service_name": service_name,
                "instances": instances,
                "total": len(instances)
            }
        except Exception as e:
            logger.error(f"List service instances error: {e}", exc_info=True)
            return {
                "error": str(e),
                "service_name": service_name,
                "instances": [],
                "total": 0
            }
    
    # ==================== 管理操作端点 ====================
    
    @router.post("/admin/routes/reload", tags=["管理"])
    async def reload_routes(
        route_service = Depends(get_route_service)
    ) -> Dict[str, Any]:
        """
        重新加载路由配置
        """
        try:
            result = await route_service.reload_routes()
            return {
                "status": "success",
                "message": "Routes reloaded successfully",
                "routes_count": result.get("routes_count", 0)
            }
        except Exception as e:
            logger.error(f"Reload routes error: {e}", exc_info=True)
            return {
                "status": "error",
                "message": str(e)
            }
    
    @router.post("/admin/services/refresh", tags=["管理"])
    async def refresh_services(
        load_balancer_service = Depends(get_load_balancer_service)
    ) -> Dict[str, Any]:
        """
        刷新服务实例状态
        """
        try:
            result = await load_balancer_service.refresh_services()
            return {
                "status": "success",
                "message": "Services refreshed successfully",
                "services_count": result.get("services_count", 0)
            }
        except Exception as e:
            logger.error(f"Refresh services error: {e}", exc_info=True)
            return {
                "status": "error",
                "message": str(e)
            }
    
    @router.get("/admin/config", tags=["管理"])
    async def get_gateway_config(
        gateway_service = Depends(get_gateway_service)
    ) -> Dict[str, Any]:
        """
        获取网关配置信息
        """
        try:
            config_info = await gateway_service.get_config_info()
            return config_info
        except Exception as e:
            logger.error(f"Get config error: {e}", exc_info=True)
            return {
                "error": str(e),
                "config": {}
            }
    
    # ==================== 调试端点（仅开发环境） ====================
    
    @router.get("/debug/request-info", tags=["调试"], include_in_schema=False)
    async def debug_request_info(request: Request) -> Dict[str, Any]:
        """
        调试：显示请求信息
        """
        return {
            "method": request.method,
            "url": str(request.url),
            "headers": dict(request.headers),
            "path_params": request.path_params,
            "query_params": dict(request.query_params),
            "client": request.client.host if request.client else None
        }
    
    # ==================== 核心网关路由（必须放在最后作为fallback）====================
    
    # WebSocket路由处理
    @router.websocket("/ws/{path:path}")
    async def websocket_handler(websocket, path: str):
        """
        WebSocket请求处理器
        处理WebSocket连接和消息转发
        """
        try:
            websocket_proxy = get_websocket_proxy()
            if not websocket_proxy:
                await websocket.close(code=1011, reason="WebSocket proxy not available")
                return
            
            # 处理WebSocket连接
            success = await websocket_proxy.handle_websocket(websocket, f"/ws/{path}")
            if not success:
                logger.warning(f"WebSocket处理失败: /ws/{path}")
                
        except Exception as e:
            logger.error(f"WebSocket处理异常: {e}", exc_info=True)
            try:
                await websocket.close(code=1011, reason="Internal server error")
            except:
                pass
    
    @router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
    async def gateway_handler(
        request: Request, 
        path: str,
        gateway_service = Depends(get_gateway_service)
    ) -> Response:
        """
        网关主要请求处理器
        处理所有需要转发的请求（fallback路由）
        """
        try:
            return await gateway_service.handle_request(request)
        except HTTPException:
            raise
        except Exception as e:
            logger.error(f"Gateway handler error: {e}", exc_info=True)
            raise HTTPException(status_code=500, detail="Internal gateway error")
    
    return router


def create_api_routes() -> APIRouter:
    """
    创建API路由（用于版本化API）
    
    Returns:
        APIRouter: API路由器实例
    """
    api_router = APIRouter(prefix="/api/v1")
    
    @api_router.get("/gateway/info", tags=["API"])
    async def gateway_info() -> Dict[str, Any]:
        """
        获取网关基本信息
        """
        return {
            "name": "RedFire API Gateway",
            "version": "1.0.0",
            "description": "基于RedFire框架的统一API网关",
            "status": "running"
        }
    
    @api_router.get("/gateway/websocket/status", tags=["API", "WebSocket"])
    async def websocket_status() -> Dict[str, Any]:
        """
        获取WebSocket服务状态
        """
        websocket_proxy = get_websocket_proxy()
        if not websocket_proxy:
            return {
                "success": False,
                "message": "WebSocket代理未初始化",
                "data": None
            }
        
        try:
            connection_info = websocket_proxy.get_connection_info()
            return {
                "success": True,
                "message": "WebSocket状态获取成功",
                "data": connection_info,
                "timestamp": datetime.now().isoformat()
            }
        except Exception as e:
            logger.error(f"获取WebSocket状态失败: {e}", exc_info=True)
            return {
                "success": False,
                "message": f"获取WebSocket状态失败: {str(e)}",
                "data": None
            }
    
    @api_router.websocket("/market/ws/market-data")
    async def websocket_market_data_proxy(websocket):
        """
        市场数据WebSocket代理端点
        处理实时市场数据WebSocket连接
        """
        from fastapi import WebSocket, WebSocketDisconnect
        
        websocket_proxy = get_websocket_proxy()
        if not websocket_proxy:
            logger.error("WebSocket proxy not initialized")
            try:
                await websocket.close(code=1011, reason="Proxy not available")
            except:
                pass
            return
        
        try:
            logger.info("Accepting WebSocket connection for market data...")
            success = await websocket_proxy.handle_websocket(
                websocket, 
                "/api/v1/market/ws/market-data"
            )
            if not success:
                logger.warning("WebSocket proxy handling failed for market data")
        except WebSocketDisconnect:
            logger.info("WebSocket client disconnected normally")
        except Exception as e:
            logger.error(f"WebSocket proxy error: {e}", exc_info=True)
            try:
                await websocket.close(code=1011, reason="Internal error")
            except:
                pass
    
    return api_router
